package com.probiz.estore.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.exception.VelocityException;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.content.SystemMessage;
import com.probiz.estore.common.model.system.MsgTemplate;
import com.probiz.estore.common.util.CurrencyConverter;
import com.probiz.estore.common.util.DateConverter;
import com.probiz.estore.content.service.SystemMessageManager;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.core.util.VelocityUtil4DB;
import com.probiz.estore.system.service.MsgSendManager;
import com.probiz.estore.system.service.MsgTemplateManager;
import com.probiz.estore.system.service.SmsQueueManager;
import com.probiz.estore.system.util.MailEngine;
import com.probiz.estore.system.util.MsgTemplateConstants;

public class MsgSendManagerImpl extends GenericManagerImpl<MsgTemplate> implements
		MsgSendManager {
	
	private MsgTemplateManager	msgTemplateManager	= null;

	private MailEngine		mailEngine		= null;
	
	private VelocityUtil4DB		velocityUtil ;
	
	private SystemMessageManager systemMessageManager;
	
	private SmsQueueManager		 smsQueueManager;
	
	public void setMsgTemplateManager(MsgTemplateManager msgTemplateManager) {
		this.msgTemplateManager = msgTemplateManager;
	}

	public void setMailEngine(MailEngine mailEngine) {
		this.mailEngine = mailEngine;
	}

	public void setVelocityUtil(VelocityUtil4DB velocityUtil) {
		this.velocityUtil = velocityUtil;
	}

	public void setSystemMessageManager(SystemMessageManager systemMessageManager) {
		this.systemMessageManager = systemMessageManager;
	}

	public void setSmsQueueManager(SmsQueueManager smsQueueManager) {
		this.smsQueueManager = smsQueueManager;
	}

	//private SmsQueueManager smsQueueManager;
	@Override
	protected void initManager() {

	}

	/**
	 * 判断是否启用邮件/系统消息/手机短信的发送
	 * @param msgTemplate  模板
	 * @return
	 */
	public Boolean msgTemplateIsUse(MsgTemplate msgTemplate) {
		if (null == msgTemplate.getStatus()) {
			return false;
		}else if (msgTemplate.getStatus() == MsgTemplateConstants.MSGTEMPLATE_IS_USE) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 发送邮件/系统消息/手机短信
	 * @param msgType        发送邮件/系统消息/手机短信类型
	 * @param msgVariables   邮件/系统消息/手机短信模板变量实体
	 * @param emailTos       邮件接收人
	 * @param customerIds    系统消息接收人
	 * @param phones         手机短信接收人
	 */
	public void sendMsg(Integer msgType, Map msgVariables, String[] emailTos,
			String[] customerIds, String[] phones) {
		List<MsgTemplate> msgTemplateList = getMsgTemplateList(msgType);
		if (null != msgTemplateList && !msgTemplateList.isEmpty()) {
			for (MsgTemplate msgTemplate : msgTemplateList) {
				/*** 获取模板，填充数据，发送信息*/
				if (msgTemplateIsUse(msgTemplate)) {
					if(msgTemplate.getType() == MsgTemplateConstants.MSGTEMPLATE_TYPE_EMAIL){
						/***发送邮件**/
						this.sendEmail(msgTemplate, msgVariables, emailTos);
					}else if(msgTemplate.getType() == MsgTemplateConstants.MSGTEMPLATE_TYPE_PHONE){
						/***发送手机短信**/
						this.sendPhoneMsg(msgTemplate, msgVariables, phones);
					}else if(msgTemplate.getType() == MsgTemplateConstants.MSGTEMPLATE_TYPE_STAND){
						/***发送系统消息**/
						this.sendSystemMsg(msgTemplate, msgVariables, customerIds);
					}
				}
			}
		}
	}

	/**
	 * 获取模板
	 * @param templateItem
	 * @return
	 */
	protected List<MsgTemplate> getMsgTemplateList(Integer templateItem){
		List<MsgTemplate> msgTemplateList  = msgTemplateManager.getDefaultMsgTemplateList(templateItem);
		return msgTemplateList;
	}
	
	/**
	 * 发送邮件
	 * @param msgTemplate   邮件模板
	 * @param msgVariables  邮件标签变量实体
	 * @param emailTos      邮件接收人
	 */
	protected void sendEmail(MsgTemplate msgTemplate, Map<String, Object> msgVariables, String[] emailTos){
		if(null != emailTos && emailTos.length > 0){
			if(StringUtils.isNotBlank(msgTemplate.getContent() )){
				mailEngine.sendSimpleTemplateMail4(msgTemplate.getContent(), msgVariables, emailTos);
			}
		}
	}
	/**
	 * 发送系统消息
	 * @param msgTemplate  
	 * @param msgVariables  
	 * @param customerIds
	 */
	protected void sendSystemMsg(MsgTemplate msgTemplate, Map<String, Object> msgVariables, String[] customerIds){
		if(null != customerIds && customerIds.length > 0){
			String modelContent = "";
			msgVariables.put("companyInfo", ConfigUtil.getInstance().getCompanyInfo());
			msgVariables.put("dateConverter", new DateConverter());
			msgVariables.put("currencyConverter", new CurrencyConverter());
			String siteUrl = ConfigUtil.getInstance().getStoreFrontSiteUrl();
			msgVariables.put(Constants.CONTEXT_PATH, siteUrl);
			msgVariables.put("mediaPath", siteUrl + "/media/");
			if (ContextUtil.getServletContext() != null) {
				msgVariables.put("applicationScope", ContextUtil.getServletContext());
				msgVariables.put(Constants.CONFIG, ContextUtil.getServletContext()
						.getAttribute(Constants.CONFIG));
			}
			for(String customerId : customerIds){
				Integer temp = Integer.parseInt(customerId);
				if(null != msgTemplate.getContent()){
					try {
						modelContent = velocityUtil.mergeTemplateIntoString(msgTemplate.getContent(), msgVariables);
					} catch (VelocityException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					systemMessageManager.addSystemMessage(modelContent, SystemMessage.MESSAGE_TYPE_ORDER_MESSAGE, temp);
				}
			}
		}
	}
	
	/**
	 * 发送手机短信
	 * @param msgTemplate
	 * @param msgVariables
	 * @param customerIds
	 */
	protected void sendPhoneMsg(MsgTemplate msgTemplate, Map<String, Object> msgVariables, String[] phones){
		if(null != phones && phones.length > 0){
			String modelContent = "";
			msgVariables.put("companyInfo", ConfigUtil.getInstance().getCompanyInfo());
			msgVariables.put("dateConverter", new DateConverter());
			msgVariables.put("currencyConverter", new CurrencyConverter());
			String siteUrl = ConfigUtil.getInstance().getStoreFrontSiteUrl();
			msgVariables.put(Constants.CONTEXT_PATH, siteUrl);
			msgVariables.put("mediaPath", siteUrl + "/media/");
			if (ContextUtil.getServletContext() != null) {
				msgVariables.put("applicationScope", ContextUtil.getServletContext());
				msgVariables.put(Constants.CONFIG, ContextUtil.getServletContext()
						.getAttribute(Constants.CONFIG));
			}
			for(String phoneNum : phones){
				if(StringUtils.isNotEmpty(phoneNum) && null != msgTemplate.getContent()){
					try {
						modelContent = velocityUtil.mergeTemplateIntoString(msgTemplate.getContent(), msgVariables);
					} catch (VelocityException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					msgVariables.clear();
					msgVariables = null;
					smsQueueManager.addSmsQueue(modelContent, phoneNum, null);
				}
			}
		}
	}
	@Override
	protected void preDelete(MsgTemplate entity) {

	}

	@Override
	protected void preSave(MsgTemplate entity) {

	}

}
